package com.baomidou.springwind.controller.supply;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.springwind.common.business.network;
import com.baomidou.springwind.controller.BaseController;
import com.baomidou.springwind.controller.NodeData;
import com.baomidou.springwind.entity.*;
import com.baomidou.springwind.mapper.*;
import com.baomidou.springwind.pojo.SiteSelection;
import com.baomidou.springwind.service.NetworkCostService;
import com.baomidou.springwind.service.NetworkCostMapService;
import com.baomidou.springwind.service.NetworkSupplyService;
import com.baomidou.springwind.service.ProjectService;
import com.baomidou.springwind.utils.ParamMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 物流网络规划成本性
 * </p>
 *
 * @Author huangtao
 * @Date 2017-8-21
 */
@Controller
@RequestMapping("/network/supply")
public class CostingController extends BaseController {

    @Autowired
    private NetworkSupplyService networkSupplyService;
    @Autowired
    private NetworkCostMapDao networkCostMapDao;
    @Autowired
    private NetworkSupplyDao networkSupplyDao;

    @Autowired
    private ProjectService projectService;
    @Autowired
    private NetworkCostService networkCostService;
    @Autowired
    private NetworkReliabilityDao networkReliabilityDao;
    @Autowired
    private NetworkDepotDao networkDepotDao;
    @Autowired
    private NetworkCustomerDao networkCustomerDao;
    @Autowired
    private NetworkDepotGoodsDao networkDepotGoodsDao;
    @Autowired
    private NetworkAlgorithmStateDao networkAlgorithmStateDao;
    @Autowired
    private NetworkAdvanceTimeDao networkAdvanceTimeDao;

    /**
     * 成本
     */
    @RequestMapping("/costing")
    @Permission("1001")
    public String response(Model model){
       /* EntityWrapper<NetworkCost> wrapper = new EntityWrapper<NetworkCost>();
        wrapper.eq("batch_id",getProjectId());
        wrapper.eq("type1", 2);
        model.addAttribute("prjList", networkDepotDao.selectList(wrapper));
        */
        return pjaxPath("/lpp/network/supply/costing/main", model);
    }

    /**
     * 反应性数据展示
     * @return
     */
    @ResponseBody
    @RequestMapping("/costing/getAllData")
    @Permission("1001")
    public String getAllData() {
        boolean lena = advanceTime();
        JSONObject ret=new JSONObject();
        EntityWrapper<NetworkDepot> wrapper1 = new EntityWrapper<NetworkDepot>();
        wrapper1.eq("batch_id", getProjectId());
        wrapper1.eq("depot_level",1);
        List<NetworkDepot> list1= networkDepotDao.selectList(wrapper1);

        EntityWrapper<NetworkDepot> wrapper2 = new EntityWrapper<NetworkDepot>();
        wrapper2.eq("batch_id", getProjectId());
        wrapper2.eq("depot_level",2);
        List<NetworkDepot> list2= networkDepotDao.selectList(wrapper2);

        String validates = networkCostService.validate(getProjectId());

        //查看算法需要的基础数据是否完整，如不完整，则提示终止
        if(list1.size()==0||list2.size()==0||validates.length()>0){
            return callbackFail(validates);
        }

        String state;
        state=buildFalse(list1,list2,lena);
       // buildFalseData();
        if(state.equals("算法运算完成")){
            ret=dealJson();
            return callbackSuccess(ret);
        }else{
            return  callbackFail(state);
        }
    }

    /**
     * 开始算法
     * @return
     */
    @RequestMapping("/costing/getAllData1")
    @Permission("1001")
    public void getAllData1() {
        buildFalseData();
    }


    /**
     * 反应性数据展示
     * @return
     */
    @ResponseBody
    @RequestMapping("/costing/getDataMap")
    @Permission("1001")
    public String getDataMap() {
        Map<SiteSelection, List<SiteSelection>> map0 = new HashMap<SiteSelection, List<SiteSelection>>();
        JSONArray jsonArray0 = new JSONArray();

            List<NetworkCostMap> list0=getMap1();
            map0=buildMap1(list0);
            jsonArray0 = network.buildMap(map0);//地图1的json数据
        return callbackSuccess(jsonArray0);
    }

    //现状的一级配送中心单独点信息
    @ResponseBody
    @Permission("1001")
    @RequestMapping("/costing/getDataMap1")
    public String getDataMap1() {
        JSONObject data = new JSONObject();
        List<NetworkCostMap> maps = getMap1();
        if(maps.size()==0){
            String message="查询数据为空";
            return callbackFail(message);
        }
        String startnode=null;
        Random random = new Random(100);
        JSONObject map1 = new JSONObject();
        JSONArray map2 = new JSONArray();
        for(int i=0;i<maps.size();i++){
            JSONArray array = new JSONArray();
            array.add(maps.get(i).getLng1().substring(0,6));
            array.add(maps.get(i).getLat1().substring(0,6));
            map1.put(maps.get(i).getStart(),array);

            JSONObject object = new JSONObject();
            object.put("name",maps.get(i).getStart());
            object.put("value",random.nextInt());
            map2.add(object);
        }
        data.put("map1",map1);
        data.put("map2",map2);
        return callbackSuccess(data);
    }

    //现状的二级配送中心单独点信息
    @ResponseBody
    @Permission("1001")
    @RequestMapping("/costing/getDataMap3")
    public String getDataMap3() {
        JSONObject data = new JSONObject();
        List<NetworkCostMap> maps = getMap2();
        if(maps.size()==0){
            String message="查询数据为空";
            return callbackFail(message);
        }
        String startnode=null;
        Random random = new Random(100);
        JSONObject map1 = new JSONObject();
        JSONArray map2 = new JSONArray();
        for(int i=0;i<maps.size();i++){
            JSONArray array = new JSONArray();
            array.add(maps.get(i).getLng2().substring(0,6));
            array.add(maps.get(i).getLat2().substring(0,6));
            map1.put(maps.get(i).getEnd(),array);

            JSONObject object = new JSONObject();
            object.put("name",maps.get(i).getEnd());
            object.put("value",random.nextInt());
            map2.add(object);
        }
        data.put("map1",map1);
        data.put("map2",map2);
        return callbackSuccess(data);
    }

    //现状的连接点信息
    @ResponseBody
    @Permission("1001")
    @RequestMapping("/costing/getDataMap2")
    public String getDataMap2() {
        JSONObject data = new JSONObject();
        List<NetworkCostMap> maps0 = getMap1();
        List<NetworkCostMap> maps = getMap2();
        if(maps.size()==0){
            String message="查询数据为空";
            return callbackFail(message);
        }
        String startnode=null;
        Random random = new Random(1);
        JSONObject map1 = new JSONObject();
        JSONArray map2 = new JSONArray();
        for(int i=0;i<maps0.size();i++){
            JSONArray array = new JSONArray();
            array.add(maps0.get(i).getLng1().substring(0,6));
            array.add(maps0.get(i).getLat1().substring(0,6));
            map1.put(maps0.get(i).getStart(),array);
        }
        for(int i=0;i<maps.size();i++){
            JSONArray array = new JSONArray();
            array.add(maps.get(i).getLng2());
            array.add(maps.get(i).getLat2());
            map1.put(maps.get(i).getEnd(),array);
        }

        for(int i=0;i<maps0.size();i++){
            String start=maps0.get(i).getStart();
            JSONArray array1 = new JSONArray();
            for(int j=0;j<maps.size();j++){
                if(start.equals(maps.get(j).getStart())){
                    JSONObject object1 = new JSONObject();
                    object1.put("name",start);
                        JSONObject object2 = new JSONObject();
                        object2.put("name",maps.get(j).getEnd());
                        object2.put("value",5);
                        JSONArray array2 = new JSONArray();
                        array2.add(object1);
                        array2.add(object2);
                        array1.add(array2);
                }
            }
            JSONArray array3 = new JSONArray();
            array3.add(start);
            array3.add(array1);
            map2.add(array3);
        }
        data.put("map1",map1);
        data.put("map2",map2);
        return callbackSuccess(data);
    }

    /**
     * 生成现状地图需要的数据
     * @return
     */
    public Map<SiteSelection, List<SiteSelection>> buildmap2(){
        Map<SiteSelection, List<SiteSelection>> map = new HashMap<SiteSelection, List<SiteSelection>>();
        ParamMap<String,Object> map1=new ParamMap<String, Object>();
        map1.put("batchId",getProjectId());
        List<Map<String, Object>> mapList=networkDepotDao.selectMaps1(map1);
        int i=0,j=mapList.size();
        while (i<j){
                List<SiteSelection> selections = new ArrayList<SiteSelection>();
                SiteSelection site1 = new SiteSelection();
                site1.setName(mapList.get(i).get("name1").toString());
                site1.setCoordinateX(BigDecimal.valueOf(Double.valueOf(mapList.get(i).get("lng1").toString())));
                site1.setCoordinateY(BigDecimal.valueOf(Double.valueOf(mapList.get(i).get("lat1").toString())));
                SiteSelection site2 = new SiteSelection();
                site2.setName(mapList.get(i).get("name2").toString());
                site2.setCoordinateX(BigDecimal.valueOf(Double.valueOf(mapList.get(i).get("lng2").toString())));
                site2.setCoordinateY(BigDecimal.valueOf(Double.valueOf(mapList.get(i).get("lat2").toString())));
                selections.add(site2);
                i++;
                selections=addMaps(site1,selections,mapList,i,j);
                map.put(site1,selections);
        }
        return map;
    }
    public List<SiteSelection> addMaps(SiteSelection site1,List<SiteSelection> selections,List<Map<String, Object>> mapList,int i,int j){
        if(i<j){
            if(site1.getName().equals(mapList.get(i).get("name1"))){
                SiteSelection site2 = new SiteSelection();
                site2.setName(mapList.get(i).get("name2").toString());
                site2.setCoordinateX(BigDecimal.valueOf(Double.valueOf(mapList.get(i).get("lng2").toString())));
                site2.setCoordinateY(BigDecimal.valueOf(Double.valueOf(mapList.get(i).get("lat2").toString())));
                selections.add(site2);
                i++;
                selections=addMaps(site1,selections,mapList,i,j);
            }
        }
        return selections;
    }



    /**
     * select数据展示
     * @return
     */
    @ResponseBody
    @RequestMapping("/costing/getSelect")
    @Permission("1001")
    public String getSelect() {
        JSONArray ret = new JSONArray();
        EntityWrapper<NetworkCost> wrapper = new EntityWrapper<NetworkCost>();
        wrapper.eq("batch_id", getProjectId());
        wrapper.eq("type1",2);
        wrapper.eq("type2",request.getParameter("nowold"));
        NetworkCost list = networkCostService.selectOne(wrapper);
        JSONObject jsonObject=JSONObject.parseObject(list.getJson());
        for(Map.Entry<String,Object> entry:jsonObject.entrySet()){
            ret.add(entry.getKey());
        }
        return callbackSuccess(ret);
    }

    /**
     * 获取一级配送中心分组地图信息
     * @return
     */
    public List<NetworkCostMap> getMap1(){
        EntityWrapper<NetworkCostMap> wrapper = new EntityWrapper<NetworkCostMap>();
        wrapper.eq("batch_id", getProjectId());
        wrapper.eq("type",request.getParameter("type"));
        wrapper.groupBy("start");
        String string = request.getParameter("selected");
        if(string.length()>0){
            wrapper.in("start",string.split(","));
        }
        List<NetworkCostMap> list = networkCostMapDao.selectList(wrapper);
        return list;
    }

    /**
     * 获取所有优化/未优化的所有的地图信息
     * @return
     */
    public List<NetworkCostMap> getMap2(){
        EntityWrapper<NetworkCostMap> wrapper = new EntityWrapper<NetworkCostMap>();
        wrapper.eq("batch_id", getProjectId());
        wrapper.eq("type",request.getParameter("type"));
        String string = request.getParameter("selected");
        if(string.length()>0){
            wrapper.in("start",string.split(","));
        }
        List<NetworkCostMap> list = networkCostMapDao.selectList(wrapper);
        return list;
    }



    /**
     * 对优化后的地图信息，通过list0生成对应的关系
     * @param list0
     * @return
     */
    public Map<SiteSelection, List<SiteSelection>> buildMap1(List<NetworkCostMap> list0){
        Map<SiteSelection, List<SiteSelection>> map0=new HashMap<SiteSelection, List<SiteSelection>>();
        SiteSelection s1;
        for(int i=0;i<list0.size();i++){
                s1=new SiteSelection();
                s1.setName(list0.get(i).getStart());
                s1.setOrder(new BigDecimal(100));
                s1.setCoordinateX(new BigDecimal(list0.get(i).getLng1()));
                s1.setCoordinateY(new BigDecimal(list0.get(i).getLat1()));
                s1.setLnglatId(list0.get(i).getId());
                map0.put(s1,null);
        }
        List<SiteSelection> selections0;
        SiteSelection selection0;
        EntityWrapper<NetworkCostMap> wrapper = new EntityWrapper<NetworkCostMap>();
        wrapper.eq("batch_id", getProjectId());
        wrapper.eq("type",request.getParameter("type"));
        List<NetworkCostMap> list = networkCostMapDao.selectList(wrapper);
        for (Map.Entry<SiteSelection, List<SiteSelection>> entry:map0.entrySet()){
            selections0=new ArrayList<SiteSelection>();
            for(int i=0;i<list.size();i++){
                if(list.get(i).getStart().toString().equals(entry.getKey().getName().toString())){
                    selection0=new SiteSelection();
                    selection0.setName(list.get(i).getEnd());
                    selection0.setCoordinateX(new BigDecimal(list.get(i).getLng2()));
                    selection0.setCoordinateY(new BigDecimal(list.get(i).getLat2()));
                    selection0.setOrder(new BigDecimal(100));
                    selections0.add(selection0);
                }
            }
            entry.setValue(selections0);
        }
        return map0;
    }


    /**
     * 获取用户处理时长，修改提前期
     */
    public boolean advanceTime(){
        String time=request.getParameter("time");
        if(time==""){
            return true;
        }
        EntityWrapper<NetworkAdvanceTime> wrapper3 = new EntityWrapper<NetworkAdvanceTime>();
        wrapper3.eq("batch_id", getProjectId());
        List<NetworkAdvanceTime> list3=networkAdvanceTimeDao.selectList(wrapper3);
        if(list3.size()>0){
            if(Integer.valueOf(time)==Integer.valueOf(list3.get(0).getDealTime())){
                return true;
            }else{
                ParamMap<String,Object> pm=new ParamMap<String, Object>();
                pm.put("batchId",getProjectId());
                pm.put("dealTime",time);
                pm.put("old",list3.get(0).getDealTime());
                networkAdvanceTimeDao.updateDeal(pm);
                return false;
            }
        }
        return true;
    }

    /**
     * 从数据库里面的数据转为json格式
     * @param
     * @return
     */
    public JSONObject dealJson(){
        updateResult();
        EntityWrapper<NetworkCost> wrapper3 = new EntityWrapper<NetworkCost>();
        wrapper3.eq("batch_id", getProjectId());
        wrapper3.eq("type2",request.getParameter("nowold"));
        wrapper3.eq("type",1);
        wrapper3.orderBy("type1");
        List<NetworkCost> cost=networkCostService.selectList(wrapper3);

        JSONObject ret=new JSONObject();
        String string = request.getParameter("selected");
        String center[];
        if(string.length()==0){
            JSONObject object =JSONObject.parseObject(cost.get(1).getJson());
            int i=0;
            for(Map.Entry<String,Object> entry:object.entrySet()){
                i++;
            }
            center=new String[i];
            int j=0;
            for(Map.Entry<String,Object> entry:object.entrySet()){
                center[j]=entry.getKey().toString();
                j++;
            }
        }else{
            center=string.split(",");
        }
        JSONArray array0 = new JSONArray();
        JSONArray array1 = new JSONArray();
        JSONArray array2 = new JSONArray();
        JSONArray array4 = new JSONArray();
        JSONArray array5 = new JSONArray();
        JSONArray array6 = new JSONArray();
        JSONArray array8 = new JSONArray();
        JSONArray array10 = new JSONArray();
        JSONArray array11 = new JSONArray();
        JSONArray array12 = new JSONArray();
        JSONArray array14 = new JSONArray();
        JSONArray array16 = new JSONArray();
        JSONArray array18 = new JSONArray();
        double list1=center.length;
        double list2=0;
        Integer list3=0;
        double list4=0;
        double list5=0;
        Integer list6=0;
        double list7=0;
        for(int i=0;i<center.length;i++){
            JSONObject object1=JSONObject.parseObject(cost.get(0).getJson());
            array0.add(center[i]);
            String str2=object1.get(center[i]).toString();
            array2.add(str2);
            list3=list3+Integer.parseInt(str2.substring(0,str2.indexOf(".")));

            JSONObject object2=JSONObject.parseObject(cost.get(1).getJson());
            array4.add(object2.get(center[i]));
            list4=list4+Double.valueOf(object2.get(center[i]).toString());

            JSONObject object3=JSONObject.parseObject(cost.get(2).getJson());
            JSONObject object31=JSONObject.parseObject(object3.get(center[i]).toString());
            for(HashMap.Entry<String,Object> entry:object31.entrySet()){
                list2++;
                array5.add(entry.getKey());
                JSONObject object = new JSONObject();
                object.put("name",entry.getKey());
                object.put("value",entry.getValue());
                array6.add(object);
            }

            JSONObject object4=JSONObject.parseObject(cost.get(3).getJson());
            array8.add(object4.get(center[i]));
            list5=list5+Double.valueOf(object4.get(center[i]).toString());

            JSONObject object5=JSONObject.parseObject(cost.get(4).getJson());
            String str10=object5.get(center[i]).toString();
            array10.add(str10);
            list6=list6+Integer.parseInt(str10.substring(0,str10.indexOf(".")));

            JSONObject object6=JSONObject.parseObject(cost.get(5).getJson());
            JSONObject object61=JSONObject.parseObject(object6.get(center[i]).toString());
            for(HashMap.Entry<String,Object> entry:object61.entrySet()){
                array11.add(entry.getKey());
                JSONObject object = new JSONObject();
                object.put("name",entry.getKey());
                object.put("value",entry.getValue());
                array12.add(object);
            }

            JSONObject object7=JSONObject.parseObject(cost.get(6).getJson());
            String str14=object7.get(center[i]).toString();
            array14.add(str14);
            list7=list7+Double.valueOf(str14.substring(0,str14.indexOf(".")));

            JSONObject object8=JSONObject.parseObject(cost.get(7).getJson());
            array16.add(object8.get(center[i]));

            JSONObject object9=JSONObject.parseObject(cost.get(8).getJson());
            array18.add(object9.get(center[i]));
        }
        ret.put("arr1",array0);
        ret.put("arr2",array2);
        ret.put("arr3",array0);
        ret.put("arr4",array4);
        ret.put("arr5",array5);
        ret.put("arr6",array6);
        ret.put("arr7",array0);
        ret.put("arr8",array8);
        ret.put("arr9",array0);
        ret.put("arr10",array10);
        ret.put("arr11",array11);
        ret.put("arr12",array12);
        ret.put("arr13",array0);
        ret.put("arr14",array14);
        ret.put("arr15",array0);
        ret.put("arr16",array16);
        ret.put("arr17",array0);
        ret.put("arr18",array18);
        ret.put("list1",list1);
        ret.put("list2",list2);
        ret.put("list3",list3);
        ret.put("list4",list4);
        ret.put("list5",list5);
        ret.put("list6",list6);
        ret.put("list7",list7);
        return ret;
    }

    /**
     * 对算法结果再进行处理
     */
    public void updateResult(){
        if(testUpdateResult()==false){
            EntityWrapper<NetworkCost> wrapper3 = new EntityWrapper<NetworkCost>();
            wrapper3.eq("batch_id", getProjectId());
            wrapper3.eq("type2",request.getParameter("nowold"));
            wrapper3.orderBy("type1");
            List<NetworkCost> list3=networkCostService.selectList(wrapper3);
            wrapper3.eq("type",1);
            networkCostService.delete(wrapper3);
            if(request.getParameter("nowold").equals("1")){
                JSONObject object2 = buildObject2(list3.get(1));
                updateResult4(list3.get(0),object2);
                updateResult2(list3.get(1));
                updateResult3(list3.get(2),object2);
                updateResult2(list3.get(3));
                updateResult4(list3.get(4),object2);
                updateResult3(list3.get(5),object2);
                updateResult2(list3.get(6));
                updateResult2(list3.get(7));
                updateResult5(list3.get(8));
                updateResult7(list3.get(0),object2,request.getParameter("nowold"));
            }else{
                JSONObject object1 = JSONObject.parseObject(list3.get(13).getJson());
                JSONObject object2 = JSONObject.parseObject(object1.get("1").toString());
                updateResult4(list3.get(0),object2);
                updateResult2(list3.get(1));
                updateResult3(list3.get(2),object2);
                updateResult2(list3.get(3));
                updateResult4(list3.get(4),object2);
                updateResult3(list3.get(5),object2);
                updateResult2(list3.get(6));
                updateResult2(list3.get(7));
                updateResult5(list3.get(8));
                updateResult2(list3.get(9));
                updateResult2(list3.get(10));
                updateResult7(list3.get(0),object2,request.getParameter("nowold"));
            }
        }
    }

    /**
     * 把现状的一级到二级的关系  转换成json格式
     * @return
     */
    public JSONObject buildObject2(NetworkCost cost){
        JSONObject object = new JSONObject();
        EntityWrapper<NetworkDepot> wrapper3 = new EntityWrapper<NetworkDepot>();
        wrapper3.eq("batch_id", getProjectId());
        wrapper3.eq("type",0);
        wrapper3.eq("depot_level",1);
        List<NetworkDepot> cost1 = networkDepotDao.selectList(wrapper3);
        for (int i=0;i<cost1.size();i++){
            EntityWrapper<NetworkDepot> wrapper4 = new EntityWrapper<NetworkDepot>();
            wrapper4.eq("batch_id", getProjectId());
            wrapper4.eq("type",0);
            wrapper4.eq("depot_level",2);
            wrapper4.eq("p_id",cost1.get(i).getId());
            List<NetworkDepot> cost2 = networkDepotDao.selectList(wrapper4);
            String buffer=cost2.get(0).getDepotName();
            if(cost2.size()>1){
                for(int i1=1;i1<cost2.size();i1++){
                    buffer=buffer+","+cost2.get(i1).getDepotName();
                }
            }
            object.put(cost1.get(i).getDepotName(),buffer);
        }
        return object;
    }

    /**
     * 不需要转换的数据
     * @param cost1
     */
    public void updateResult2(NetworkCost cost1){
        cost1.setType(1);
        networkCostService.insert(cost1);
    }
    /**
     * 对给的数据转为地图展示需要的数据
     * @param cost1
     */
    public void updateResult5(NetworkCost cost1){
        JSONObject object = JSONObject.parseObject(cost1.getJson());
        JSONObject object2 = JSONObject.parseObject(object.get("1").toString());
        JSONObject jsonObject = new JSONObject();
        String str[];
        for(Map.Entry<String,Object> entry:object2.entrySet()){
            JSONObject object3 = new JSONObject();
            JSONObject object1 =JSONObject.parseObject(entry.getValue().toString());
            double sum=0;
            for(Map.Entry<String,Object> entry1:object1.entrySet()){
                sum=sum+Double.valueOf(entry1.getValue().toString());
            }
            jsonObject.put(entry.getKey(),sum);
        }
        NetworkCost cost = new NetworkCost();
        cost.setType1(cost1.getType1());
        cost.setType2(cost1.getType2());
        cost.setJson(jsonObject.toJSONString());
        cost.setBatchId(cost1.getBatchId());
        cost.setType(1);
        networkCostService.insert(cost);
    }
    /**
     * 对给的数据转为地图展示需要的数据
     * @param cost1
     * @param
     */
    public void updateResult3(NetworkCost cost1,JSONObject object2){
        JSONObject object = JSONObject.parseObject(cost1.getJson());
        JSONObject jsonObject = new JSONObject();
        String str[];
        for(Map.Entry<String,Object> entry:object2.entrySet()){
            JSONObject object3 = new JSONObject();
            str=entry.getValue().toString().split(",");
            for (int i=0;i<str.length;i++){
                object3.put(str[i],object.get(str[i]));
            }
            jsonObject.put(entry.getKey(),object3);
        }
        NetworkCost cost = new NetworkCost();
        cost.setType1(cost1.getType1());
        cost.setType2(cost1.getType2());
        cost.setJson(jsonObject.toJSONString());
        cost.setBatchId(cost1.getBatchId());
        cost.setType(1);
        networkCostService.insert(cost);
    }
    /**
     * 对给的数据转为地图展示需要的数据
     * @param cost1
     */
    public void updateResult4(NetworkCost cost1,JSONObject object2){
        JSONObject object = JSONObject.parseObject(cost1.getJson());

        JSONObject object3 = new JSONObject();
        for(Map.Entry<String,Object> entry:object2.entrySet()){
            object3.put(entry.getKey(),0);
        }
        JSONObject object4 = object3;
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1;
        for(Map.Entry<String,Object> entry:object.entrySet()){
            jsonObject1=JSONObject.parseObject(entry.getValue().toString());
            for(Map.Entry<String,Object> entry1:object3.entrySet()){
                object4.put(entry1.getKey(),Double.valueOf(object4.get(entry1.getKey()).toString())+ Double.valueOf(jsonObject1.get(entry1.getKey()).toString()));
            }
        }
        NetworkCost cost = new NetworkCost();
        cost.setType1(cost1.getType1());
        cost.setType2(cost1.getType2());
        cost.setJson(object4.toJSONString());
        cost.setBatchId(cost1.getBatchId());
        cost.setType(1);
        networkCostService.insert(cost);
    }




    /**
     * 对给的数据转为地图展示需要的数据,二级中心到客户的数据
     * @param cost
     */
    public void updateResult6(NetworkCost cost){
        JSONObject objects=JSONObject.parseObject(cost.getJson());
        objects.toString();
        JSONObject jsonObject=new JSONObject();
        JSONArray array1;
        JSONArray array2;
        JSONArray array3=new JSONArray();
        JSONArray array4=new JSONArray();
        List<NetworkCostMap> list=new ArrayList<NetworkCostMap>();
        NetworkCostMap cost1;
        for(Map.Entry<String,Object> entry:objects.entrySet()){
            cost1=new NetworkCostMap();
            cost1.setBatchId(cost.getBatchId());
            cost1.setEnd(entry.getKey());
            EntityWrapper<NetworkCustomer> wrapper3 = new EntityWrapper<NetworkCustomer>();
            wrapper3.eq("batch_id", getProjectId());
            wrapper3.eq("customer_name",entry.getKey());
            List<NetworkCustomer> list3=networkCustomerDao.selectList(wrapper3);
            cost1.setLng2(list3.get(0).getCustomerLng());
            cost1.setLat2(list3.get(0).getCustomerLat());
            JSONObject objects1=JSONObject.parseObject(entry.getValue().toString());
            for(Map.Entry<String,Object> entry1:objects1.entrySet()){
                cost1.setStart(entry1.getKey());
                cost1.setValue(entry1.getValue().toString());
                break;
            }
            list.add(cost1);
            networkCostMapDao.insert(cost1);
        }
        EntityWrapper<NetworkCostMap> wrapper4 = new EntityWrapper<NetworkCostMap>();
        wrapper4.eq("batch_id", getProjectId());
        wrapper4.groupBy("start");
        List<NetworkCostMap> list4=networkCostMapDao.selectList(wrapper4);
        for(int i=0;i<list4.size();i++){
            EntityWrapper<NetworkDepot> wrapper5 = new EntityWrapper<NetworkDepot>();
            wrapper5.eq("batch_id", getProjectId());
            wrapper5.eq("depot_name",list4.get(i).getStart());
            List<NetworkDepot> list5=networkDepotDao.selectList(wrapper5);
            ParamMap<String,Object> pm=new ParamMap<String, Object>();
            pm.put("lng1",list5.get(0).getDepotLng());
            pm.put("lat1",list5.get(0).getDepotLat());
            pm.put("batchId",getProjectId());
            pm.put("start",list4.get(i).getStart());
            networkCostMapDao.updateLng(pm);
        }
    }

    /**
     * 对给的数据转为地图展示需要的数据,一级到二级的数据
     * @param cost
     */
    public void updateResult7(NetworkCost cost,JSONObject objects3,String type){
        EntityWrapper<NetworkCostMap> wrapper1 = new EntityWrapper<NetworkCostMap>();
        wrapper1.eq("batch_id", getProjectId());
        wrapper1.eq("type",type);
        networkCostMapDao.delete(wrapper1);

        NetworkCostMap cost1;
        for(Map.Entry<String,Object> entry:objects3.entrySet()){

            EntityWrapper<NetworkDepot> wrapper3 = new EntityWrapper<NetworkDepot>();
            wrapper3.eq("batch_id", getProjectId());
            wrapper3.eq("depot_name",entry.getKey());
            List<NetworkDepot> list3=networkDepotDao.selectList(wrapper3);

            String center[]=entry.getValue().toString().split(",");

            for(int i=0;i<center.length;i++){
                cost1=new NetworkCostMap();
                cost1.setBatchId(cost.getBatchId());
                cost1.setStart(entry.getKey());
                cost1.setEnd(center[i]);
                cost1.setValue("40");
                cost1.setLng1(list3.get(0).getDepotLng());
                cost1.setLat1(list3.get(0).getDepotLat());
                EntityWrapper<NetworkDepot> wrapper5 = new EntityWrapper<NetworkDepot>();
                wrapper5.eq("batch_id", getProjectId());
                wrapper5.eq("depot_name",center[i]);
                List<NetworkDepot> list5=networkDepotDao.selectList(wrapper5);
                cost1.setLng2(list5.get(0).getDepotLng());
                cost1.setLat2(list5.get(0).getDepotLat());
                cost1.setType(Integer.valueOf(type));
                networkCostMapDao.insert(cost1);
            }
        }

    }




    /**
     * 判断是否需要对数据进行再处理
     * @return
     */
    public Boolean testUpdateResult(){
        EntityWrapper<NetworkCost> wrapper3 = new EntityWrapper<NetworkCost>();
        wrapper3.eq("batch_id", getProjectId());
        wrapper3.eq("type2",request.getParameter("nowold"));
        wrapper3.eq("type",1);
        List<NetworkCost> list3=networkCostService.selectList(wrapper3);
        if(list3.size()==0){
            return false;
        }
        return true;
    }

    /**
     * 返回算法是否有结果，1为有结果，0为还在计算
     * @param list1
     * @param list2
     * @return
     */
    public String buildFalse(List<NetworkDepot> list1,List<NetworkDepot> list2,boolean lean){
        System.out.println(lean+"------------------");
        String type1="算法运算完成";
        String type2="算法正在运行";
        EntityWrapper<NetworkAlgorithmState> wrapper2 = new EntityWrapper<NetworkAlgorithmState>();
        wrapper2.eq("batch_id", getProjectId());
        wrapper2.eq("algorithm",1);
        wrapper2.orderBy("state",false);
        List<NetworkAlgorithmState> list3= networkAlgorithmStateDao.selectList(wrapper2);
        if(list3.size()==0){
            NetworkAlgorithmState state=new NetworkAlgorithmState();
            state.setBatchId(Long.valueOf(getProjectId()));
            state.setAlgorithm("1");
            state.setState("0");
            int idl=networkAlgorithmStateDao.insert(state);
            buildFalseData();
            List<NetworkAlgorithmState> list4= networkAlgorithmStateDao.selectList(wrapper2);
            if(list4.size()>0&&"1".equals(list4.get(0).getState())){
                return "算法运算完成";
            }else {
                return "算法正在运行,请等待";
            }
        }
        if(list3.size()>0&&list3.get(0).getState().equals("0")){
            return "算法正在运行,请等待";
        }
        if(list3.size()>0&&list3.get(0).getState().equals("1")){
            if(lean==true){
                return "算法运算完成";
            }else{
                networkAlgorithmStateDao.delete(wrapper2);
                buildFalse(list1,list2,true);
                List<NetworkAlgorithmState> list4= networkAlgorithmStateDao.selectList(wrapper2);
                if(list4.size()>0&&list4.get(0).getState().equals("1")){
                    return "算法运算完成";
                }else {
                    return "算法正在运行,请等待";
                }
            }

        }
        return "算法正在运行";
    }

    /**
     * 类似于算法
     * @return
     */
    public void buildFalseData(){

        int  parm1=Integer.valueOf(getProjectId());
        String parm2="second";
        String cmd = "cmd /k start C:\\optmizier-network\\network-optimizing\\result.bat";// pass
        cmd=cmd+" "+parm1+" ";
        try {
            Process ps = Runtime.getRuntime().exec(cmd);
            InputStream in = ps.getInputStream();
            int c;
            while ((c = in.read()) != -1) {
                System.out.print(c);// 如果你不需要看输出，这行可以注销掉
            }
            in.close();
            ps.waitFor();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("child thread donn");

        EntityWrapper<NetworkAlgorithmState> wrapper2 = new EntityWrapper<NetworkAlgorithmState>();
        wrapper2.eq("batch_id", getProjectId());
        wrapper2.eq("algorithm",1);
        networkAlgorithmStateDao.delete(wrapper2);
        NetworkAlgorithmState state=new NetworkAlgorithmState();
        state.setBatchId(Long.valueOf(getProjectId()));
        state.setState("1");
        state.setAlgorithm("1");
        networkAlgorithmStateDao.insert(state);

    }

    /**
     * 第10个图的展示
     * @return
     */
    @ResponseBody
    @RequestMapping("/costing/getData10")
    @Permission("1001")
    public String getData10() {
        JSONObject ret=new JSONObject();
        EntityWrapper<NetworkCost> wrapper1 = new EntityWrapper<NetworkCost>();
        wrapper1.eq("batch_id", getProjectId());
        wrapper1.eq("type1",10);
        wrapper1.eq("type2",1);
        NetworkCost cost= networkCostService.selectOne(wrapper1);
    //    ret.put("arr1", net.sf.json.JSONObject.fromObject(cost.getJson()).get("arr1"));
    //    ret.put("arr2", net.sf.json.JSONObject.fromObject(cost.getJson()).get("arr2"));
        return callbackSuccess(ret);
    }
    /**
     * 第10个图的下属图展示
     * @return
     */
    @ResponseBody
    @RequestMapping("/costing/getData91")
    @Permission("1001")
    public String getData91() {
        JSONObject ret=new JSONObject();
        EntityWrapper<NetworkCost> wrapper1 = new EntityWrapper<NetworkCost>();
        wrapper1.eq("batch_id", getProjectId());
        wrapper1.eq("type1",9);
        wrapper1.eq("type2",2);
        wrapper1.eq("center",request.getParameter("center"));
        NetworkCost cost= networkCostService.selectOne(wrapper1);
        ret.put("arr1", JSONObject.parseObject(cost.getJson()).get("arr1"));
        ret.put("arr2", JSONObject.parseObject(cost.getJson()).get("arr2"));
        return callbackSuccess(ret);
    }

    /**
     * 第10个图的展示
     * @return
     */
    @ResponseBody
    @RequestMapping("/costing/getData11")
    @Permission("1001")
    public String getData11() {
        JSONObject ret=new JSONObject();
        EntityWrapper<NetworkCost> wrapper1 = new EntityWrapper<NetworkCost>();
        wrapper1.eq("batch_id", getProjectId());
        wrapper1.eq("type1",11);
        wrapper1.eq("type2",1);
        NetworkCost cost= networkCostService.selectOne(wrapper1);
   //     ret.put("arr1", net.sf.json.JSONObject.fromObject(cost.getJson()).get("arr1"));
   //     ret.put("arr2", net.sf.json.JSONObject.fromObject(cost.getJson()).get("arr2"));
        return callbackSuccess(ret);
    }
    /**
     * 第10个图的下属图展示
     * @return
     */
    @ResponseBody
    @RequestMapping("/costing/getData111")
    @Permission("1001")
    public String getData111() {
        JSONObject ret=new JSONObject();
        EntityWrapper<NetworkCost> wrapper1 = new EntityWrapper<NetworkCost>();
        wrapper1.eq("batch_id", getProjectId());
        wrapper1.eq("type1",11);
        wrapper1.eq("type2",0);
        wrapper1.eq("center",request.getParameter("name"));
        NetworkCost cost= networkCostService.selectOne(wrapper1);
    //    ret.put("arr1", net.sf.json.JSONObject.fromObject(cost.getJson()).get("arr1"));
    //    ret.put("arr2", net.sf.json.JSONObject.fromObject(cost.getJson()).get("arr2"));
        return callbackSuccess(ret);
    }

    /**
     * 第10个图的展示
     * @return
     */
    @ResponseBody
    @RequestMapping("/costing/getData12")
    @Permission("1001")
    public String getData12() {
        JSONObject ret=new JSONObject();
        EntityWrapper<NetworkCost> wrapper1 = new EntityWrapper<NetworkCost>();
        wrapper1.eq("batch_id", getProjectId());
        wrapper1.eq("type1",12);
        wrapper1.eq("type2",1);
        NetworkCost cost= networkCostService.selectOne(wrapper1);
   //     ret.put("arr1", net.sf.json.JSONObject.fromObject(cost.getJson()).get("arr1"));
    //    ret.put("arr2", net.sf.json.JSONObject.fromObject(cost.getJson()).get("arr2"));
        return callbackSuccess(ret);
    }
    /**
     * 第10个图的下属图展示
     * @return
     */
    @ResponseBody
    @RequestMapping("/costing/getData121")
    @Permission("1001")
    public String getData121() {
        JSONObject ret=new JSONObject();
        EntityWrapper<NetworkCost> wrapper1 = new EntityWrapper<NetworkCost>();
        wrapper1.eq("batch_id", getProjectId());
        wrapper1.eq("type1",12);
        wrapper1.eq("type2",2);
        wrapper1.eq("center",request.getParameter("center"));
        NetworkCost cost= networkCostService.selectOne(wrapper1);
        ret.put("arr1", JSONObject.parseObject(cost.getJson()).get("arr1"));
        ret.put("arr2", JSONObject.parseObject(cost.getJson()).get("arr2"));
        return callbackSuccess(ret);
    }

    /**
     * 第10个图的展示
     * @return
     */
    @ResponseBody
    @RequestMapping("/costing/getData13")
    @Permission("1001")
    public String getData13() {
        JSONObject ret=new JSONObject();
        EntityWrapper<NetworkCost> wrapper1 = new EntityWrapper<NetworkCost>();
        wrapper1.eq("batch_id", getProjectId());
        wrapper1.eq("type1",13);
        wrapper1.eq("type2",1);
        NetworkCost cost= networkCostService.selectOne(wrapper1);
    //    ret.put("arr1", net.sf.json.JSONObject.fromObject(cost.getJson()).get("arr1"));
     //   ret.put("arr2", net.sf.json.JSONObject.fromObject(cost.getJson()).get("arr2"));
        return callbackSuccess(ret);
    }
    /**
     * 第10个图的下属图展示
     * @return
     */
    @ResponseBody
    @RequestMapping("/costing/getData131")
    @Permission("1001")
    public String getData131() {
        JSONObject ret=new JSONObject();
        EntityWrapper<NetworkCost> wrapper1 = new EntityWrapper<NetworkCost>();
        wrapper1.eq("batch_id", getProjectId());
        wrapper1.eq("type1",13);
        wrapper1.eq("type2",0);
        wrapper1.eq("center",request.getParameter("name"));
        NetworkCost cost= networkCostService.selectOne(wrapper1);
     //   ret.put("arr1", net.sf.json.JSONObject.fromObject(cost.getJson()).get("arr1"));
     //   ret.put("arr2", net.sf.json.JSONObject.fromObject(cost.getJson()).get("arr2"));
        return callbackSuccess(ret);
    }


}

